package com.hzj.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzj.pojo.FullUser;
import com.hzj.service.FullUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

//自定义UserDetailsService 接口
@Service
public class CustomUserService implements UserDetailsService {

    @Autowired
    //注入service层用来访问数据库
    FullUserService fus;


    public UserDetails loadUserByUsername(String username) {
        System.out.println("表单提交的用户名:"+username);
        //查询数据库用户，使用的mybatis-plus
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username", username);
        FullUser fullUser = fus.getOne(wrapper);
        //判断用户是否存在
        if (fullUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        System.out.println(fullUser);
        //添加权限,多个权限通过逗号隔开,(工具类中有三个方法,具体可以看源码)
        List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
//        list.add(new SimpleGrantedAuthority(""))
//       存入用户名与加密后的密码,user(是security的内置类，不是自己创建的)对象是实现至UserDetails的类，所以可以直接返回
        User user = new User(fullUser.getUsername(), new BCryptPasswordEncoder().encode(fullUser.getYesapiXqwUserPassword()), list);
        System.out.println(user.getUsername()+"|"+user.getPassword());
        return user;

    }

}